package org.example.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.dao.MenuDao;
import org.example.dao.UserDao;
import org.example.domain.LoginUser;
import org.example.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class UserDetailsServicesImpl implements UserDetailsService {


    @Resource
    private UserDao userDao;
    @Resource
    private MenuDao menuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //获取用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        User user = userDao.selectOne(lambdaQueryWrapper);

        if(user == null){
            throw new UsernameNotFoundException("没有找到该用户");
        }
        //设置用户角色
        user.setRole(userDao.getRoleByUserId(user.getUserId()));
        user.setPassword(userDao.getPasswordById(user.getUserId()));

        //获取用户权限信息
        List<String> permissions = menuDao.getGrantedAuthority(user.getUserId());

        return new LoginUser(user, permissions);
    }

}
